﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace z.Controllers {
	[z.Filters.InitializeSimpleMembership]
	public class OccasionController : Controller {
		public ActionResult Index() {
			App.resetDB();
			return View(App.db.Occasions);
		}
		public ActionResult Products(int OccasionID) {
			return View("~/Views/Product/ProductsList.aspx", App.db.Occasions.Where(x => x.ID == OccasionID).Single().Occasion_Detail.Select(x => x.Product).ToList());
		}
		[Authorize(Roles = "Admin,Mod")]
		public ActionResult Administer() {
			App.resetDB();
			return View("Table");
		}
		[Authorize(Roles="Admin,Mod")]
		public ActionResult _Add() {
			var m = new m.db.Occasion();
			return PartialView("_Row", m);
		}
		[HttpPost]
		[Authorize(Roles = "Admin,Mod")]
		public ActionResult _Delete(int ID) {
			var m = App.db.Occasions.Where(x => x.ID == ID).Single();
			//m.Messengers.Clear();
			//m.Occasion_Detail.Clear();
			foreach (var x in m.Messengers.ToList()) {
				App.db.Messengers.Remove(x);
			}
			foreach (var x in m.Occasion_Detail.ToList()) {
				App.db.Occasion_Details.Remove(x);
			}
			App.db.Occasions.Remove(m);
			App.db.SaveChanges();
			WebSocketController.SendMessenger("Occasion," + m.ID);
			return PartialView("Null");
		}
		[HttpPost]
		[Authorize(Roles = "Admin,Mod")]
		public ActionResult _Edit(m.db.Occasion In) {
			App.resetDB();
			var isAdd = App.db.Occasions.Where(x => x.ID == In.ID).Count() == 0;
			var m = isAdd ? App.db.Occasions.Add(new m.db.Occasion())
				: App.db.Occasions.Where(x => x.ID == In.ID).Single();
			m.Banner = System.Web.HttpUtility.HtmlDecode(In.Banner);
			if (ModelState.IsValid) {
				try {
					App.db.SaveChanges();
				} catch (Exception ex) {
					return null;
				}
			}
			WebSocketController.SendMessenger("Occasion," + m.ID);
			return PartialView("_Row", m);
		}
		[Authorize(Roles = "Mod,Admin")]
		public ActionResult _Show(int ID) {
			var m = App.db.Occasions.Where(x => x.ID == ID).Single();
			return PartialView("_Row", m);
		}
	}
}
